Abstract Class yii\db\BaseActiveRecord
Inheritance | yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\Object |
---|---|
Implements | ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\db\ActiveRecordInterface |
Uses Traits | yii\base\ArrayableTrait |
Subclasses | examples\shop\Product, spinitron\dynamicAr\DynamicActiveRecord, tests\unit\data\BaseRecord, tests\unit\data\ar\Category, tests\unit\data\ar\Customer, tests\unit\data\ar\Item, tests\unit\data\ar\NullValues, tests\unit\data\ar\Order, tests\unit\data\ar\OrderItem, tests\unit\data\ar\OrderItemWithNullFK, tests\unit\data\ar\OrderWithNullFK, tests\unit\data\ar\Profile, tests\unit\data\ar\Type, tests\unit\data\dar\MissingDynColumn, tests\unit\data\dar\Person, tests\unit\data\dar\Product, tests\unit\data\dar\Supplier, yii\db\ActiveRecord |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php |
ActiveRecord is the base class for classes representing relational data in terms of objects.
See yii\db\ActiveRecord for a concrete implementation.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$activeValidators | \yii\validators\Validator[] | The validators applicable to the current $scenario. | yii\base\Model |
$attributes | array | Attribute values (name => value). | yii\base\Model |
$behaviors | \yii\base\Behavior[] | List of behaviors attached to this component | yii\base\Component |
$dirtyAttributes | array | The changed attribute values (name-value pairs) | yii\db\BaseActiveRecord |
$errors | array | Errors for all attributes or the specified attribute. | yii\base\Model |
$firstErrors | array | The first errors. | yii\base\Model |
$isNewRecord | boolean | Whether the record is new and should be inserted when calling save(). | yii\db\BaseActiveRecord |
$iterator | ArrayIterator | An iterator for traversing the items in the list. | yii\base\Model |
$oldAttributes | array | The old attribute values (name-value pairs) | yii\db\BaseActiveRecord |
$oldPrimaryKey | mixed | The old primary key value. | yii\db\BaseActiveRecord |
$primaryKey | mixed | The primary key value. | yii\db\BaseActiveRecord |
$relatedRecords | array | An array of related records indexed by relation names. | yii\db\BaseActiveRecord |
$scenario | string | The scenario that this model is in. | yii\base\Model |
$validators | ArrayObject|\yii\validators\Validator[] | All the validators declared in the model. | yii\base\Model |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Component |
__construct() | Constructor. | yii\base\Object |
__get() | PHP getter magic method. | yii\db\BaseActiveRecord |
__isset() | Checks if a property value is null. | yii\db\BaseActiveRecord |
__set() | PHP setter magic method. | yii\db\BaseActiveRecord |
__unset() | Sets a component property to be null. | yii\db\BaseActiveRecord |
activeAttributes() | Returns the attribute names that are subject to validation in the current scenario. | yii\base\Model |
addError() | Adds a new error to the specified attribute. | yii\base\Model |
addErrors() | Adds a list of errors. | yii\base\Model |
afterDelete() | This method is invoked after deleting a record. | yii\db\BaseActiveRecord |
afterFind() | This method is called when the AR object is created and populated with the query result. | yii\db\BaseActiveRecord |
afterSave() | This method is called at the end of inserting or updating a record. | yii\db\BaseActiveRecord |
afterValidate() | This method is invoked after validation ends. | yii\base\Model |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
attributeHints() | Returns the attribute hints. | yii\base\Model |
attributeLabels() | Returns the attribute labels. | yii\base\Model |
attributes() | Returns the list of all attribute names of the record. | yii\db\ActiveRecordInterface |
beforeDelete() | This method is invoked before deleting a record. | yii\db\BaseActiveRecord |
beforeSave() | This method is called at the beginning of inserting or updating a record. | yii\db\BaseActiveRecord |
beforeValidate() | This method is invoked before validation starts. | yii\base\Model |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
className() | Returns the fully qualified name of this class. | yii\base\Object |
clearErrors() | Removes errors for all attributes or a single attribute. | yii\base\Model |
createValidators() | Creates validator objects based on the validation rules specified in rules(). | yii\base\Model |
delete() | Deletes the table row corresponding to this active record. | yii\db\BaseActiveRecord |
deleteAll() | Deletes rows in the table using the provided conditions. | yii\db\BaseActiveRecord |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
equals() | Returns a value indicating whether the given active record is the same as the current one. | yii\db\BaseActiveRecord |
extraFields() | Returns the list of fields that can be expanded further and returned by toArray(). | yii\db\BaseActiveRecord |
fields() | Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. | yii\db\BaseActiveRecord |
find() | Creates an yii\db\ActiveQueryInterface instance for query purpose. | yii\db\ActiveRecordInterface |
findAll() | Returns a list of active record models that match the specified primary key value(s) or a set of column values. | yii\db\BaseActiveRecord |
findOne() | Returns a single active record model instance by a primary key or an array of column values. | yii\db\BaseActiveRecord |
formName() | Returns the form name that this model class should use. | yii\base\Model |
generateAttributeLabel() | Generates a user friendly attribute label based on the give attribute name. | yii\base\Model |
getActiveValidators() | Returns the validators applicable to the current $scenario. | yii\base\Model |
getAttribute() | Returns the named attribute value. | yii\db\BaseActiveRecord |
getAttributeHint() | Returns the text hint for the specified attribute. | yii\db\BaseActiveRecord |
getAttributeLabel() | Returns the text label for the specified attribute. | yii\db\BaseActiveRecord |
getAttributes() | Returns attribute values. | yii\base\Model |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
getDb() | Returns the connection used by this AR class. | yii\db\ActiveRecordInterface |
getDirtyAttributes() | Returns the attribute values that have been modified since they are loaded or saved most recently. | yii\db\BaseActiveRecord |
getErrors() | Returns the errors for all attribute or a single attribute. | yii\base\Model |
getFirstError() | Returns the first error of the specified attribute. | yii\base\Model |
getFirstErrors() | Returns the first error of every attribute in the model. | yii\base\Model |
getIsNewRecord() | Returns a value indicating whether the current record is new. | yii\db\BaseActiveRecord |
getIterator() | Returns an iterator for traversing the attributes in the model. | yii\base\Model |
getOldAttribute() | Returns the old value of the named attribute. | yii\db\BaseActiveRecord |
getOldAttributes() | Returns the old attribute values. | yii\db\BaseActiveRecord |
getOldPrimaryKey() | Returns the old primary key value(s). | yii\db\BaseActiveRecord |
getPrimaryKey() | Returns the primary key value(s). | yii\db\BaseActiveRecord |
getRelatedRecords() | Returns all populated related records. | yii\db\BaseActiveRecord |
getRelation() | Returns the relation object with the specified name. | yii\db\BaseActiveRecord |
getScenario() | Returns the scenario that this model is used in. | yii\base\Model |
getValidators() | Returns all the validators declared in rules(). | yii\base\Model |
hasAttribute() | Returns a value indicating whether the model has an attribute with the specified name. | yii\db\BaseActiveRecord |
hasErrors() | Returns a value indicating whether there is any validation error. | yii\base\Model |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMany() | Declares a has-many relation. |
yii\db\BaseActiveRecord |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasOne() | Declares a has-one relation. |
yii\db\BaseActiveRecord |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes the object. | yii\db\BaseActiveRecord |
insert() | Inserts the record into the database using the attribute values of this record. | yii\db\ActiveRecordInterface |
instantiate() | Creates an active record instance. | yii\db\BaseActiveRecord |
isAttributeActive() | Returns a value indicating whether the attribute is active in the current scenario. | yii\base\Model |
isAttributeChanged() | Returns a value indicating whether the named attribute has been changed. | yii\db\BaseActiveRecord |
isAttributeRequired() | Returns a value indicating whether the attribute is required. | yii\base\Model |
isAttributeSafe() | Returns a value indicating whether the attribute is safe for massive assignments. | yii\base\Model |
isPrimaryKey() | Returns a value indicating whether the given set of attributes represents the primary key for this model | yii\db\BaseActiveRecord |
isRelationPopulated() | Check whether the named relation has been populated with records. | yii\db\BaseActiveRecord |
link() | Establishes the relationship between two models. | yii\db\BaseActiveRecord |
load() | Populates the model with the data from end user. | yii\base\Model |
loadMultiple() | Populates a set of models with the data from end user. | yii\base\Model |
markAttributeDirty() | Marks an attribute dirty. | yii\db\BaseActiveRecord |
off() | Detaches an existing event handler from this component. | yii\base\Component |
offsetExists() | Returns whether there is an element at the specified offset. | yii\db\BaseActiveRecord |
offsetGet() | Returns the element at the specified offset. | yii\base\Model |
offsetSet() | Sets the element at the specified offset. | yii\base\Model |
offsetUnset() | Sets the element value at the specified offset to null. | yii\db\BaseActiveRecord |
on() | Attaches an event handler to an event. | yii\base\Component |
onUnsafeAttribute() | This method is invoked when an unsafe attribute is being massively assigned. | yii\base\Model |
optimisticLock() | Returns the name of the column that stores the lock version for implementing optimistic locking. | yii\db\BaseActiveRecord |
populateRecord() | Populates an active record object using a row of data from the database/storage. | yii\db\BaseActiveRecord |
populateRelation() | Populates the named relation with the related records. | yii\db\BaseActiveRecord |
primaryKey() | Returns the primary key name(s) for this AR class. | yii\db\ActiveRecordInterface |
refresh() | Repopulates this active record with the latest data. | yii\db\BaseActiveRecord |
rules() | Returns the validation rules for attributes. | yii\base\Model |
safeAttributes() | Returns the attribute names that are safe to be massively assigned in the current scenario. | yii\base\Model |
save() | Saves the current record. | yii\db\BaseActiveRecord |
scenarios() | Returns a list of scenarios and the corresponding active attributes. | yii\base\Model |
setAttribute() | Sets the named attribute value. | yii\db\BaseActiveRecord |
setAttributes() | Sets the attribute values in a massive way. | yii\base\Model |
setIsNewRecord() | Sets the value indicating whether the record is new. | yii\db\BaseActiveRecord |
setOldAttribute() | Sets the old value of the named attribute. | yii\db\BaseActiveRecord |
setOldAttributes() | Sets the old attribute values. | yii\db\BaseActiveRecord |
setScenario() | Sets the scenario for the model. | yii\base\Model |
toArray() | Converts the model into an array. | yii\base\ArrayableTrait |
trigger() | Triggers an event. | yii\base\Component |
unlink() | Destroys the relationship between two models. | yii\db\BaseActiveRecord |
unlinkAll() | Destroys the relationship in current model. | yii\db\BaseActiveRecord |
update() | Saves the changes to this active record into the associated database table. | yii\db\BaseActiveRecord |
updateAll() | Updates the whole table using the provided attribute values and conditions. | yii\db\BaseActiveRecord |
updateAllCounters() | Updates the whole table using the provided counter changes and conditions. | yii\db\BaseActiveRecord |
updateAttributes() | Updates the specified attributes. | yii\db\BaseActiveRecord |
updateCounters() | Updates one or several counter columns for the current AR object. | yii\db\BaseActiveRecord |
validate() | Performs the data validation. | yii\base\Model |
validateMultiple() | Validates multiple models. | yii\base\Model |
Protected Methods
Method | Description | Defined By |
---|---|---|
findByCondition() | Finds ActiveRecord instance(s) by the given condition. | yii\db\BaseActiveRecord |
resolveFields() | Determines which fields can be returned by toArray(). | yii\base\ArrayableTrait |
updateInternal() | yii\db\BaseActiveRecord |
Events
Event | Type | Description | Defined By |
---|---|---|---|
EVENT_AFTER_DELETE | \yii\db\Event | An event that is triggered after a record is deleted. | yii\db\BaseActiveRecord |
EVENT_AFTER_FIND | \yii\db\Event | An event that is triggered after the record is created and populated with query result. | yii\db\BaseActiveRecord |
EVENT_AFTER_INSERT | \yii\db\Event | An event that is triggered after a record is inserted. | yii\db\BaseActiveRecord |
EVENT_AFTER_UPDATE | \yii\db\Event | An event that is triggered after a record is updated. | yii\db\BaseActiveRecord |
EVENT_AFTER_VALIDATE | \yii\base\Event | An event raised at the end of validate() | yii\base\Model |
EVENT_BEFORE_DELETE | \yii\base\ModelEvent | An event that is triggered before deleting a record. | yii\db\BaseActiveRecord |
EVENT_BEFORE_INSERT | \yii\base\ModelEvent | An event that is triggered before inserting a record. | yii\db\BaseActiveRecord |
EVENT_BEFORE_UPDATE | \yii\base\ModelEvent | An event that is triggered before updating a record. | yii\db\BaseActiveRecord |
EVENT_BEFORE_VALIDATE | \yii\base\ModelEvent | An event raised at the beginning of validate(). | yii\base\Model |
EVENT_INIT | \yii\db\Event | An event that is triggered when the record is initialized via init(). | yii\db\BaseActiveRecord |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
SCENARIO_DEFAULT | 'default' | The name of the default scenario. | yii\base\Model |
Property Details
The changed attribute values (name-value pairs)
Whether the record is new and should be inserted when calling save().
The old attribute values (name-value pairs)
The old primary key value. An array (column name => column value) is returned if the primary key
is composite or $asArray
is true. A string is returned otherwise (null will be returned if
the key value is null).
The primary key value. An array (column name => column value) is returned if the primary key
is composite or $asArray
is true. A string is returned otherwise (null will be returned if
the key value is null).
An array of related records indexed by relation names.
Method Details
PHP getter magic method.
This method is overridden so that attributes and related objects can be accessed like properties.
See also getAttribute().
public mixed __get ( $name ) | ||
$name | string | Property name |
return | mixed | Property value |
---|---|---|
throws | \yii\base\InvalidParamException | if relation name is wrong |
Checks if a property value is null.
This method overrides the parent implementation by checking if the named attribute is null or not.
public boolean __isset ( $name ) | ||
$name | string | The property name or the event name |
return | boolean | Whether the property value is null |
---|
PHP setter magic method.
This method is overridden so that AR attributes can be accessed like properties.
public void __set ( $name, $value ) | ||
$name | string | Property name |
$value | mixed | Property value |
Sets a component property to be null.
This method overrides the parent implementation by clearing the specified attribute value.
public void __unset ( $name ) | ||
$name | string | The property name or the event name |
This method is invoked after deleting a record.
The default implementation raises the EVENT_AFTER_DELETE event. You may override this method to do postprocessing after the record is deleted. Make sure you call the parent implementation so that the event is raised properly.
public void afterDelete ( ) |
This method is called when the AR object is created and populated with the query result.
The default implementation will trigger an EVENT_AFTER_FIND event. When overriding this method, make sure you call the parent implementation to ensure the event is triggered.
public void afterFind ( ) |
This method is called at the end of inserting or updating a record.
The default implementation will trigger an EVENT_AFTER_INSERT event when $insert
is true,
or an EVENT_AFTER_UPDATE event if $insert
is false. The event class used is \yii\db\AfterSaveEvent.
When overriding this method, make sure you call the parent implementation so that
the event is triggered.
public void afterSave ( $insert, $changedAttributes ) | ||
$insert | boolean | Whether this method called while inserting a record. If false, it means the method is called while updating a record. |
$changedAttributes | array | The old values of attributes that had changed and were saved.
You can use this parameter to take action based on the changes made for example send an email
when the password had changed or implement audit trail that tracks all the changes.
|
This method is invoked before deleting a record.
The default implementation raises the EVENT_BEFORE_DELETE event. When overriding this method, make sure you call the parent implementation like the following:
public function beforeDelete()
{
if (parent::beforeDelete()) {
// ...custom code here...
return true;
} else {
return false;
}
}
public boolean beforeDelete ( ) | ||
return | boolean | Whether the record should be deleted. Defaults to true. |
---|
This method is called at the beginning of inserting or updating a record.
The default implementation will trigger an EVENT_BEFORE_INSERT event when $insert
is true,
or an EVENT_BEFORE_UPDATE event if $insert
is false.
When overriding this method, make sure you call the parent implementation like the following:
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
// ...custom code here...
return true;
} else {
return false;
}
}
public boolean beforeSave ( $insert ) | ||
$insert | boolean | Whether this method called while inserting a record. If false, it means the method is called while updating a record. |
return | boolean | Whether the insertion or updating should continue. If false, the insertion or updating will be cancelled. |
---|
Deletes the table row corresponding to this active record.
This method performs the following steps in order:
- call beforeDelete(). If the method returns false, it will skip the rest of the steps;
- delete the record from the database;
- call afterDelete().
In the above step 1 and 3, events named EVENT_BEFORE_DELETE and EVENT_AFTER_DELETE will be raised by the corresponding methods.
public integer|false delete ( ) | ||
return | integer|false | The number of rows deleted, or false if the deletion is unsuccessful for some reason. Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
---|---|---|
throws | \yii\db\StaleObjectException | if optimistic locking is enabled and the data being deleted is outdated. |
throws | \yii\db\Exception | in case delete failed. |
Deletes rows in the table using the provided conditions.
WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
For example, to delete all customers whose status is 3:
Customer::deleteAll('status = 3');
public static integer deleteAll ( $condition = '', $params = [] ) | ||
$condition | string|array | The conditions that will be put in the WHERE part of the DELETE SQL. Please refer to yii\db\Query::where() on how to specify this parameter. |
$params | array | The parameters (name => value) to be bound to the query. |
return | integer | The number of rows deleted |
---|---|---|
throws | \yii\base\NotSupportedException | if not overrided |
Returns a value indicating whether the given active record is the same as the current one.
The comparison is made by comparing the table names and the primary key values of the two active records. If one of the records is new they are also considered not equal.
public boolean equals ( $record ) | ||
$record | yii\db\ActiveRecordInterface | Record to compare to |
return | boolean | Whether the two active records refer to the same row in the same database table. |
---|
Returns the list of fields that can be expanded further and returned by toArray().
This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), will their values be exported.
The default implementation returns an empty array.
You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).
The default implementation returns the names of the relations that have been populated into this record.
public array extraFields ( ) | ||
return | array | The list of expandable field names or field definitions. Please refer to fields() on the format of the return value. |
---|
Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
A field is a named element in the returned array by toArray().
This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:
function ($field, $model) {
// return field value
}
For example, the following code declares four fields:
email
: the field name is the same as the property nameemail
;firstName
andlastName
: the field names arefirstName
andlastName
, and their values are obtained from thefirst_name
andlast_name
properties;fullName
: the field name isfullName
. Its value is obtained by concatenatingfirst_name
andlast_name
.
return [
'email',
'firstName' => 'first_name',
'lastName' => 'last_name',
'fullName' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
];
In this method, you may also want to return different lists of fields based on some context information. For example, depending on $scenario or the privilege of the current application user, you may return different sets of visible fields or filter out some fields.
The default implementation of this method returns attributes() indexed by the same attribute names.
The default implementation returns the names of the columns whose values have been populated into this record.
public array fields ( ) | ||
return | array | The list of field names or field definitions. |
---|
Returns a list of active record models that match the specified primary key value(s) or a set of column values.
The method accepts:
- a scalar value (integer or string): query by a single primary key value and return an array containing the corresponding record (or an empty array if not found).
- a non-associative array: query by a list of primary key values and return the
corresponding records (or an empty array if none was found).
Note that an empty condition will result in an empty result as it will be interpreted as a search for
primary keys and not an empty
WHERE
condition. - an associative array of name-value pairs: query by a set of attribute values and return an array of records
matching all of them (or an empty array if none was found). Note that
['id' => 1, 2]
is treated as a non-associative array.
This method will automatically call the all()
method and return an array of ActiveRecord
instances. For example,
// find the customers whose primary key value is 10
$customers = Customer::findAll(10);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();
// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();
// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
public static static[] findAll ( $condition ) | ||
$condition | mixed | Primary key value or a set of column values |
return | static[] | An array of ActiveRecord instances, or an empty array if nothing matches. |
---|
Finds ActiveRecord instance(s) by the given condition.
This method is internally called by findOne() and findAll().
protected static yii\db\ActiveQueryInterface findByCondition ( $condition ) | ||
$condition | mixed | Please refer to findOne() for the explanation of this parameter |
return | yii\db\ActiveQueryInterface | The newly created ActiveQuery instance. |
---|---|---|
throws | \yii\base\InvalidConfigException | if there is no primary key defined |
Returns a single active record model instance by a primary key or an array of column values.
The method accepts:
- a scalar value (integer or string): query by a single primary key value and return the corresponding record (or null if not found).
- a non-associative array: query by a list of primary key values and return the first record (or null if not found).
- an associative array of name-value pairs: query by a set of attribute values and return a single record
matching all of them (or null if not found). Note that
['id' => 1, 2]
is treated as a non-associative array.
That this method will automatically call the one()
method and return an ActiveRecord
instance. For example,
// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);
// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();
// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
public static static|null findOne ( $condition ) | ||
$condition | mixed | Primary key value or a set of column values |
return | static|null | ActiveRecord instance matching the condition, or |
---|
Returns the named attribute value.
If this record is the result of a query and the attribute is not loaded, null will be returned.
See also hasAttribute().
public mixed getAttribute ( $name ) | ||
$name | string | The attribute name |
return | mixed | The attribute value. Null if the attribute is not set or does not exist. |
---|
Returns the text hint for the specified attribute.
If the attribute looks like relatedModel.attribute
, then the attribute will be received from the related model.
See also attributeHints().
public string getAttributeHint ( $attribute ) | ||
$attribute | string | The attribute name |
return | string | The attribute hint |
---|
Returns the text label for the specified attribute.
If the attribute looks like relatedModel.attribute
, then the attribute will be received from the related model.
See also:
public string getAttributeLabel ( $attribute ) | ||
$attribute | string | The attribute name |
return | string | The attribute label |
---|
Returns the attribute values that have been modified since they are loaded or saved most recently.
public array getDirtyAttributes ( $names = null ) | ||
$names | string[]|null | The names of the attributes whose values may be returned if they are changed recently. If null, attributes() will be used. |
return | array | The changed attribute values (name-value pairs) |
---|
Returns a value indicating whether the current record is new.
public boolean getIsNewRecord ( ) | ||
return | boolean | Whether the record is new and should be inserted when calling save(). |
---|
Returns the old value of the named attribute.
If this record is the result of a query and the attribute is not loaded, null will be returned.
See also hasAttribute().
public mixed getOldAttribute ( $name ) | ||
$name | string | The attribute name |
return | mixed | The old attribute value. Null if the attribute is not loaded before or does not exist. |
---|
Returns the old attribute values.
public array getOldAttributes ( ) | ||
return | array | The old attribute values (name-value pairs) |
---|
Returns the old primary key value(s).
This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findOne()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.
public mixed getOldPrimaryKey ( $asArray = false ) | ||
$asArray | boolean | Whether to return the primary key value as an array. If true, the return value will be an array with column name as key and column value as value. If this is false (default), a scalar value will be returned for non-composite primary key. |
return | mixed | The old primary key value. An array (column name => column value) is returned if the primary key
is composite or |
---|---|---|
throws | \yii\db\Exception | if the AR model does not have a primary key |
Returns the primary key value(s).
public mixed getPrimaryKey ( $asArray = false ) | ||
$asArray | boolean | Whether to return the primary key value as an array. If true, the return value will be an array with column names as keys and column values as values. Note that for composite primary keys, an array will always be returned regardless of this parameter value. |
return | mixed | The primary key value. An array (column name => column value) is returned if the primary key
is composite or |
---|
Returns all populated related records.
public array getRelatedRecords ( ) | ||
return | array | An array of related records indexed by relation names. |
---|
Returns the relation object with the specified name.
A relation is defined by a getter method which returns an yii\db\ActiveQueryInterface object. It can be declared in either the Active Record class itself or one of its behaviors.
public yii\db\ActiveQueryInterface|yii\db\ActiveQuery getRelation ( $name, $throwException = true ) | ||
$name | string | The relation name |
$throwException | boolean | Whether to throw exception if the relation does not exist. |
return | yii\db\ActiveQueryInterface|yii\db\ActiveQuery | The relational query object. If the relation does not exist
and |
---|---|---|
throws | \yii\base\InvalidParamException | if the named relation does not exist. |
Returns a value indicating whether the model has an attribute with the specified name.
public boolean hasAttribute ( $name ) | ||
$name | string | The name of the attribute |
return | boolean | Whether the model has an attribute with the specified name. |
---|
Declares a has-many
relation.
The declaration is returned in terms of a relational yii\db\ActiveQuery instance through which the related record can be queried and retrieved back.
A has-many
relation means that there are multiple related records matching
the criteria set by this relation, e.g., a customer has many orders.
For example, to declare the orders
relation for Customer
class, we can write
the following code in the Customer
class:
public function getOrders()
{
return $this->hasMany(Order::className(), ['customer_id' => 'id']);
}
Note that in the above, the 'customer_id' key in the $link
parameter refers to
an attribute name in the related class Order
, while the 'id' value refers to
an attribute name in the current AR class.
Call methods declared in yii\db\ActiveQuery to further customize the relation.
public yii\db\ActiveQueryInterface hasMany ( $class, $link ) | ||
$class | string | The class name of the related record |
$link | array | The primary-foreign key constraint. The keys of the array refer to
the attributes of the record associated with the |
return | yii\db\ActiveQueryInterface | The relational query object. |
---|
Declares a has-one
relation.
The declaration is returned in terms of a relational yii\db\ActiveQuery instance through which the related record can be queried and retrieved back.
A has-one
relation means that there is at most one related record matching
the criteria set by this relation, e.g., a customer has one country.
For example, to declare the country
relation for Customer
class, we can write
the following code in the Customer
class:
public function getCountry()
{
return $this->hasOne(Country::className(), ['id' => 'country_id']);
}
Note that in the above, the 'id' key in the $link
parameter refers to an attribute name
in the related class Country
, while the 'country_id' value refers to an attribute name
in the current AR class.
Call methods declared in yii\db\ActiveQuery to further customize the relation.
public yii\db\ActiveQueryInterface hasOne ( $class, $link ) | ||
$class | string | The class name of the related record |
$link | array | The primary-foreign key constraint. The keys of the array refer to
the attributes of the record associated with the |
return | yii\db\ActiveQueryInterface | The relational query object. |
---|
Initializes the object.
This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.
public void init ( ) |
Creates an active record instance.
This method is called together with populateRecord() by yii\db\ActiveQuery. It is not meant to be used for creating new records directly.
You may override this method if the instance being created depends on the row data to be populated into the record. For example, by creating a record based on the value of a column, you may implement the so-called single-table inheritance mapping.
public static static instantiate ( $row ) | ||
$row | array | Row data to be populated into the record. |
return | static | The newly created active record |
---|
Returns a value indicating whether the named attribute has been changed.
public boolean isAttributeChanged ( $name, $identical = true ) | ||
$name | string | The name of the attribute. |
$identical | boolean | Whether the comparison of new and old value is made for
identical values using |
return | boolean | Whether the attribute has been changed |
---|
Returns a value indicating whether the given set of attributes represents the primary key for this model
public static boolean isPrimaryKey ( $keys ) | ||
$keys | array | The set of attributes to check |
return | boolean | Whether the given set of attributes represents the primary key for this model |
---|
Check whether the named relation has been populated with records.
public boolean isRelationPopulated ( $name ) | ||
$name | string | The relation name (case-sensitive) |
return | boolean | Whether relation has been populated with records. |
---|
Establishes the relationship between two models.
The relationship is established by setting the foreign key value(s) in one model to be the corresponding primary key value(s) in the other model. The model with the foreign key will be saved into database without performing validation.
If the relationship involves a junction table, a new row will be inserted into the junction table which contains the primary key values from both models.
Note that this method requires that the primary key value is not null.
public void link ( $name, $model, $extraColumns = [] ) | ||
$name | string | The case sensitive name of the relationship |
$model | yii\db\ActiveRecordInterface | The model to be linked with the current one. |
$extraColumns | array | Additional column values to be saved into the junction table.
This parameter is only meaningful for a relationship involving a junction table
(i.e., a relation set with yii\db\ActiveRelationTrait::via() or |
throws | \yii\base\InvalidCallException | if the method is unable to link two models. |
---|
Marks an attribute dirty.
This method may be called to force updating a record when calling update(), even if there is no change being made to the record.
public void markAttributeDirty ( $name ) | ||
$name | string | The attribute name |
Returns whether there is an element at the specified offset.
This method is required by the interface ArrayAccess.
public boolean offsetExists ( $offset ) | ||
$offset | mixed | The offset to check on |
return | boolean | Whether there is an element at the specified offset. |
---|
Sets the element value at the specified offset to null.
This method is required by the SPL interface ArrayAccess
.
It is implicitly called when you use something like unset($model[$offset])
.
public void offsetUnset ( $offset ) | ||
$offset | mixed | The offset to unset element |
Returns the name of the column that stores the lock version for implementing optimistic locking.
Optimistic locking allows multiple users to access the same record for edits and avoids potential conflicts. In case when a user attempts to save the record upon some staled data (because another user has modified the data), a \yii\db\StaleObjectException exception will be thrown, and the update or deletion is skipped.
Optimistic locking is only supported by update() and delete().
To use Optimistic locking:
- Create a column to store the version number of each row. The column type should be
BIGINT DEFAULT 0
. Override this method to return the name of this column. - Add a
required
validation rule for the version column to ensure the version value is submitted. - In the Web form that collects the user input, add a hidden field that stores the lock version of the recording being updated.
- In the controller action that does the data updating, try to catch the \yii\db\StaleObjectException and implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
public string optimisticLock ( ) | ||
return | string | The column name that stores the lock version of a table row. If null is returned (default implemented), optimistic locking will not be supported. |
---|
Populates an active record object using a row of data from the database/storage.
This is an internal method meant to be called to create active record objects after fetching data from the database. It is mainly used by yii\db\ActiveQuery to populate the query results into active records.
When calling this method manually you should call afterFind() on the created record to trigger the afterFind Event.
public static void populateRecord ( $record, $row ) | ||
$record | yii\db\BaseActiveRecord | The record to be populated. In most cases this will be an instance created by instantiate() beforehand. |
$row | array | Attribute values (name => value) |
Populates the named relation with the related records.
Note that this method does not check if the relation exists or not.
public void populateRelation ( $name, $records ) | ||
$name | string | The relation name (case-sensitive) |
$records | yii\db\ActiveRecordInterface|array|null | The related records to be populated into the relation. |
Repopulates this active record with the latest data.
public boolean refresh ( ) | ||
return | boolean | Whether the row still exists in the database. If true, the latest data will be populated to this active record. Otherwise, this record will remain unchanged. |
---|
Saves the current record.
This method will call insert() when $isNewRecord is true, or update() when $isNewRecord is false.
For example, to save a customer record:
$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();
public boolean save ( $runValidation = true, $attributeNames = null ) | ||
$runValidation | boolean | Whether to perform validation before saving the record. If the validation fails, the record will not be saved to database. |
$attributeNames | array | List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
return | boolean | Whether the saving succeeds |
---|
Sets the named attribute value.
See also hasAttribute().
public void setAttribute ( $name, $value ) | ||
$name | string | The attribute name |
$value | mixed | The attribute value. |
throws | \yii\base\InvalidParamException | if the named attribute does not exist. |
---|
Sets the value indicating whether the record is new.
See also getIsNewRecord().
public void setIsNewRecord ( $value ) | ||
$value | boolean | Whether the record is new and should be inserted when calling save(). |
Sets the old value of the named attribute.
See also hasAttribute().
public void setOldAttribute ( $name, $value ) | ||
$name | string | The attribute name |
$value | mixed | The old attribute value. |
throws | \yii\base\InvalidParamException | if the named attribute does not exist. |
---|
Sets the old attribute values.
All existing old attribute values will be discarded.
public void setOldAttributes ( $values ) | ||
$values | array|null | Old attribute values to be set.
If set to |
Destroys the relationship between two models.
The model with the foreign key of the relationship will be deleted if $delete
is true.
Otherwise, the foreign key will be set null and the model will be saved without validation.
public void unlink ( $name, $model, $delete = false ) | ||
$name | string | The case sensitive name of the relationship. |
$model | yii\db\ActiveRecordInterface | The model to be unlinked from the current one. You have to make sure that the model is really related with the current model as this method does not check this. |
$delete | boolean | Whether to delete the model that contains the foreign key. If false, the model's foreign key will be set null and saved. If true, the model containing the foreign key will be deleted. |
throws | \yii\base\InvalidCallException | if the models cannot be unlinked |
---|
Destroys the relationship in current model.
The model with the foreign key of the relationship will be deleted if $delete
is true.
Otherwise, the foreign key will be set null and the model will be saved without validation.
Note that to destroy the relationship without removing records make sure your keys can be set to null
public void unlinkAll ( $name, $delete = false ) | ||
$name | string | The case sensitive name of the relationship. |
$delete | boolean | Whether to delete the model that contains the foreign key. |
Saves the changes to this active record into the associated database table.
This method performs the following steps in order:
- call beforeValidate() when
$runValidation
is true. If validation fails, it will skip the rest of the steps; - call afterValidate() when
$runValidation
is true. - call beforeSave(). If the method returns false, it will skip the rest of the steps;
- save the record into database. If this fails, it will skip the rest of the steps;
- call afterSave();
In the above step 1, 2, 3 and 5, events EVENT_BEFORE_VALIDATE, EVENT_BEFORE_UPDATE, EVENT_AFTER_UPDATE and EVENT_AFTER_VALIDATE will be raised by the corresponding methods.
Only the changed attribute values will be saved into database.
For example, to update a customer record:
$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();
Note that it is possible the update does not affect any row in the table. In this case, this method will return 0. For this reason, you should use the following code to check if update() is successful or not:
if ($this->update() !== false) {
// update successful
} else {
// update failed
}
public integer|boolean update ( $runValidation = true, $attributeNames = null ) | ||
$runValidation | boolean | Whether to perform validation before saving the record. If the validation fails, the record will not be inserted into the database. |
$attributeNames | array | List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
return | integer|boolean | The number of rows affected, or false if validation fails or beforeSave() stops the updating process. |
---|---|---|
throws | \yii\db\StaleObjectException | if optimistic locking is enabled and the data being updated is outdated. |
throws | \yii\db\Exception | in case update failed. |
Updates the whole table using the provided attribute values and conditions.
For example, to change the status to be 1 for all customers whose status is 2:
Customer::updateAll(['status' => 1], 'status = 2');
public static integer updateAll ( $attributes, $condition = '' ) | ||
$attributes | array | Attribute values (name-value pairs) to be saved into the table |
$condition | string|array | The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to yii\db\Query::where() on how to specify this parameter. |
return | integer | The number of rows updated |
---|---|---|
throws | \yii\base\NotSupportedException | if not overridden |
Updates the whole table using the provided counter changes and conditions.
For example, to increment all customers' age by 1,
Customer::updateAllCounters(['age' => 1]);
public static integer updateAllCounters ( $counters, $condition = '' ) | ||
$counters | array | The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters. |
$condition | string|array | The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to yii\db\Query::where() on how to specify this parameter. |
return | integer | The number of rows updated |
---|---|---|
throws | \yii\base\NotSupportedException | if not overrided |
Updates the specified attributes.
This method is a shortcut to update() when data validation is not needed and only a small set attributes need to be updated.
You may specify the attributes to be updated as name list or name-value pairs. If the latter, the corresponding attribute values will be modified accordingly. The method will then save the specified attributes into database.
Note that this method will not perform data validation and will not trigger events.
public integer updateAttributes ( $attributes ) | ||
$attributes | array | The attributes (names or name-value pairs) to be updated |
return | integer | The number of rows affected. |
---|
Updates one or several counter columns for the current AR object.
Note that this method differs from updateAllCounters() in that it only saves counters for the current AR object.
An example usage is as follows:
$post = Post::findOne($id);
$post->updateCounters(['view_count' => 1]);
See also updateAllCounters().
public boolean updateCounters ( $counters ) | ||
$counters | array | The counters to be updated (attribute name => increment value) Use negative values if you want to decrement the counters. |
return | boolean | Whether the saving is successful |
---|
See also update().
protected integer updateInternal ( $attributes = null ) | ||
$attributes | array | Attributes to update |
return | integer | Number of rows updated |
---|---|---|
throws | \yii\db\StaleObjectException |
Event Details
An event that is triggered after a record is deleted.
An event that is triggered after the record is created and populated with query result.
An event that is triggered after a record is inserted.
An event that is triggered after a record is updated.
An event that is triggered before deleting a record. You may set \yii\base\ModelEvent::isValid to be false to stop the deletion.
An event that is triggered before inserting a record. You may set \yii\base\ModelEvent::isValid to be false to stop the insertion.
An event that is triggered before updating a record. You may set \yii\base\ModelEvent::isValid to be false to stop the update.
An event that is triggered when the record is initialized via init().